package com.shockweb.common.security;

import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;

import com.shockweb.common.serializable.SerializableObject;

/**
 * 公私钥加解密
 * 
 * @author 彭明华
 * 2018年4月18日 创建
 */
public class Rsa {

    /**
     * 生成RSA密钥对(默认密钥长度为1024)
     */
    public static KeyPair generateRSAKeyPair() {
        return generateRSAKeyPair(1024);
    }

    /**
     * 生成RSA密钥对
     *
     * @param keyLength 密钥长度，范围：512～2048
     */
    public static KeyPair generateRSAKeyPair(int keyLength) {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(keyLength);
            return kpg.genKeyPair();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * 将公钥转化成xml
     * @param key
     * @return
     */
    public static String encodePublicKeyToXml(PublicKey key) {
        if (!RSAPublicKey.class.isInstance(key)) {
            return null;
        }
        RSAPublicKey pubKey = (RSAPublicKey) key;
        StringBuilder sb = new StringBuilder();

        sb.append("<RSAKeyValue>");
        sb.append("<Modulus>")
                .append(SerializableObject.base64EncodeString(TrimLeadingZero(pubKey.getModulus().toByteArray())))
                .append("</Modulus>");
        sb.append("<Exponent>")
                .append(SerializableObject.base64EncodeString(TrimLeadingZero(pubKey.getPublicExponent()
                        .toByteArray()))).append("</Exponent>");
        sb.append("</RSAKeyValue>");
        return sb.toString();
    }

    /**
     * 将xml公钥转化成PublicKey
     * @param xml
     * @return
     */
    public static PublicKey decodePublicKeyFromXml(String xml) {
        xml = xml.replaceAll("\r", "").replaceAll("\n", "");
        BigInteger modulus = new BigInteger(1, SerializableObject.base64Decode(getMiddleString(xml, "<Modulus>", "</Modulus>")));
        BigInteger publicExponent = new BigInteger(1,SerializableObject.base64Decode(getMiddleString(xml,"<Exponent>", "</Exponent>")));
        RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus,publicExponent);

        KeyFactory keyf;
        try {
            keyf = KeyFactory.getInstance("RSA");
            return keyf.generatePublic(rsaPubKey);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 将xml私钥转化成PrivateKey
     * @param xml
     * @return
     */
    public static PrivateKey decodePrivateKeyFromXml(String xml) {
        xml = xml.replaceAll("\r", "").replaceAll("\n", "");
        BigInteger modulus = new BigInteger(1, SerializableObject.base64Decode(getMiddleString(xml, "<Modulus>", "</Modulus>")));
        BigInteger publicExponent = new BigInteger(1,SerializableObject.base64Decode(getMiddleString(xml,"<Exponent>", "</Exponent>")));
        BigInteger privateExponent = new BigInteger(1,SerializableObject.base64Decode(getMiddleString(xml, "<D>","</D>")));
        BigInteger primeP = new BigInteger(1, SerializableObject.base64Decode(getMiddleString(xml, "<P>", "</P>")));
        BigInteger primeQ = new BigInteger(1, SerializableObject.base64Decode(getMiddleString(xml, "<Q>", "</Q>")));
        BigInteger primeExponentP = new BigInteger(1,SerializableObject.base64Decode(getMiddleString(xml, "<DP>","</DP>")));
        BigInteger primeExponentQ = new BigInteger(1,SerializableObject.base64Decode(getMiddleString(xml, "<DQ>","</DQ>")));
        BigInteger crtCoefficient = new BigInteger(1,SerializableObject.base64Decode(getMiddleString(xml,"<InverseQ>", "</InverseQ>")));

        RSAPrivateCrtKeySpec rsaPriKey = new RSAPrivateCrtKeySpec(modulus,
                publicExponent, privateExponent, primeP, primeQ,
                primeExponentP, primeExponentQ, crtCoefficient);

        KeyFactory keyf;
        try {
            keyf = KeyFactory.getInstance("RSA");
            return keyf.generatePrivate(rsaPriKey);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 将私钥转化成xml
     * @param key
     * @return
     */
    public static String encodePrivateKeyToXml(PrivateKey key) {
        if (!RSAPrivateCrtKey.class.isInstance(key)) {
            return null;
        }
        RSAPrivateCrtKey priKey = (RSAPrivateCrtKey) key;
        StringBuilder sb = new StringBuilder();

        sb.append("<RSAKeyValue>");
        sb.append("<Modulus>")
                .append(SerializableObject.base64EncodeString(TrimLeadingZero(priKey.getModulus().toByteArray())))
                .append("</Modulus>");
        sb.append("<Exponent>")
                .append(SerializableObject.base64EncodeString(TrimLeadingZero(priKey.getPublicExponent()
                        .toByteArray()))).append("</Exponent>");
        sb.append("<P>")
                .append(SerializableObject.base64EncodeString(priKey.getPrimeP().toByteArray()))
                .append("</P>");
        sb.append("<Q>")
                .append(SerializableObject.base64EncodeString(priKey.getPrimeQ().toByteArray()))
                .append("</Q>");
        sb.append("<DP>")
                .append(SerializableObject.base64EncodeString(priKey.getPrimeExponentP()
                        .toByteArray())).append("</DP>");
        sb.append("<DQ>")
                .append(SerializableObject.base64EncodeString(priKey.getPrimeExponentQ()
                        .toByteArray())).append("</DQ>");
        sb.append("<InverseQ>")
                .append(SerializableObject.base64EncodeString(priKey.getCrtCoefficient()
                        .toByteArray())).append("</InverseQ>");
        sb.append("<D>")
                .append(SerializableObject.base64EncodeString(priKey.getPrivateExponent()
                        .toByteArray())).append("</D>");
        sb.append("</RSAKeyValue>");
        //略去N自个字符...
        return sb.toString();
    }

    static byte[] TrimLeadingZero(byte[] values) { // 主要使用到了TrimLeadingZero方法去除前置的0.其中
        if ((0x00 == values[0]) && (values.length > 1)) {
            byte[] r = null;
            r = new byte[values.length - 1];
            System.arraycopy(values, 1, r, 0, r.length);
            return r;
        }
        return values;
    }

    /**
     * 加密
     * @param data
     * @param key
     * @return
     */
    public static byte[] encryptData(byte[] data, Key key) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 解密
     * @param encryptedData
     * @param key
     * @return
     */
    public static byte[] decryptData(byte[] encryptedData, Key key) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(encryptedData);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 签名(默认签名算法为"SHA1withRSA")
     *
     * @param data   要签名的数据
     * @param priKey 私钥
     */
    public static byte[] signData(byte[] data, PrivateKey priKey) {
        return signData(data, priKey, "SHA1withRSA");
    }

    /**
     * 签名
     *
     * @param data      要签名的数据
     * @param priKey    私钥
     * @param algorithm 签名算法
     */
    public static byte[] signData(byte[] data, PrivateKey priKey,
                                  String algorithm) {
        try {
            Signature signature = Signature.getInstance(algorithm);
            signature.initSign(priKey);
            signature.update(data);
            return signature.sign();
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 验签(默认签名算法为"SHA1withRSA")
     *
     * @param data   数据
     * @param sign   签名结果
     * @param pubKey 公钥
     */
    public static boolean verifySign(byte[] data, byte[] sign, PublicKey pubKey) {
        return verifySign(data, sign, pubKey, "SHA1withRSA");
    }

    /**
     * 验签
     * @param data      数据
     * @param sign      签名结果
     * @param pubKey    公钥
     * @param algorithm 签名算法
     */
    public static boolean verifySign(byte[] data, byte[] sign,
                                     PublicKey pubKey, String algorithm) {
        try {
            Signature signature = Signature.getInstance(algorithm);
            signature.initVerify(pubKey);
            signature.update(data);
            return signature.verify(sign);
        } catch (Exception ex) {
            return false;
        }
    }



    /**
     * 获取中间字符串
     * @param source
     * @param strHead
     * @param strTail
     * @return
     */
    private static String getMiddleString(String source, String strHead, String strTail) {
        try {
            int indexHead, indexTail;

            if (strHead == null || strHead.isEmpty()) {
                indexHead = 0;
            } else {
                indexHead = source.indexOf(strHead);
            }

            if (strTail == null || strTail.isEmpty()) {
                indexTail = source.length();
            } else {
                indexTail = source.indexOf(strTail, indexHead + strHead.length());
            }
            if (indexTail < 0) {
                indexTail = source.length();
            }

            String rtnStr = "";
            if ((indexHead >= 0) && (indexTail >= 0)) {
                rtnStr = source.substring(indexHead + strHead.length(), indexTail);
            }
            return rtnStr;
        } catch (Exception ex) {
            return "";
        }
    }
}